﻿//file: clock.cpp

#include "clock.h"
#include <QTimer>
#include <QPainter>
#include <QTime>

//全局变量
const QPointF hourHand[3] = {      //时针（三角形）
    QPoint(7, 8),
    QPoint(-7, 8),
    QPoint(0, -40)
};
const QPointF minuteHand[3] = {    //分针
    QPoint(7, 8),
    QPoint(-7, 8),
    QPoint(0, -70)
};
const QPointF secondHand[3] = {     //秒针
    QPoint(7, 8),
    QPoint(-7, 8),
    QPoint(0, -90)
};

/**
 * @brief 构造函数。开启一个定时器，用于刷新界面。
 * @param parent - 父对象
 */
Clock::Clock(QWidget *parent) : QWidget(parent)
{
    //新建一个定时器，用于刷新时钟状态
    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, [this](){
        this->update();
    });
    timer->start(1000);
}

/**
 * @brief 绘图事件。利用旋转、移动绘图坐标，来绘制时钟。
 */
void Clock::paintEvent(QPaintEvent *)
{
    QPainter painter(this);    //画家
    QPen pen;                  //画笔
    QColor hourColor(127, 0, 127);
    QColor minuteColor(0, 127, 127, 191);
    QColor secondColor(0, 160, 230, 191);



    painter.fillRect(0, 0, width(), height(), QGradient::NightFade);  //绘制背景

    painter.translate(width() / 2, height() / 2);  //将绘图的坐标系统原点放在控件的中心
    painter.setRenderHints(QPainter::Antialiasing);  //抗锯齿
    int side = qMin(width(), height());
    painter.scale(side / 250.0, side / 250.0);      //缩放坐标系统

    //绘制时钟的表盘
    painter.save();     //保存一下画家的当前状态
    for(int i = 0; i < 60; ++i)
    {
        if(i % 5 != 0)
        {
            pen.setColor(minuteColor);
            painter.setPen(pen);
            painter.drawLine(92, 0, 96, 0);
        }
        else   //每5个画一条粗线
        {
            pen.setColor(hourColor);
            painter.setPen(pen);
            painter.drawLine(88, 0, 96, 0);
        }
        painter.rotate(6);    //每次旋转 6°，60次就是360°
    }
    painter.restore();  //恢复上一次保存的画家的状态

    //绘制时针、分针、秒针
    QTime curTime = QTime::currentTime();     //当前系统时间
    painter.save();
    painter.rotate(30.0 * (curTime.hour() + curTime.minute() / 60.0));
    pen.setColor(hourColor);
    painter.setPen(pen);
    painter.setBrush(hourColor);
    painter.drawConvexPolygon(hourHand, 3);
    painter.restore();

    painter.save();
    painter.rotate(6.0 * ((curTime.minute() + curTime.second() / 60.0)));
    pen.setColor(minuteColor);
    painter.setPen(pen);
    painter.setBrush(minuteColor);
    painter.drawConvexPolygon(minuteHand, 3);
    painter.restore();

    painter.save();
    painter.rotate(6.0 * curTime.second());
    pen.setColor(secondColor);
    painter.setPen(pen);
    painter.setBrush(secondColor);
    painter.drawConvexPolygon(secondHand, 3);
    painter.restore();
}
